package indi.mozping.lock;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import java.util.Arrays;
import java.util.UUID;

public class MyRedisLock {

    private static ThreadLocal<String> local = new ThreadLocal<>();
    private static final String KEY = "KEY";


    public static boolean lock() {
        for (; ; ) {
            if (tryLock()) {
                return true;
            }
        }
    }

    public static boolean tryLock() {
        String uuid = UUID.randomUUID().toString();
        Jedis jedis = new Jedis("127.0.0.1");
        SetParams setParams = new SetParams();
        setParams.nx().px(3000);
        String ret = jedis.set(KEY, uuid, setParams);
        //String ret = jedis.set(KEY, uuid, "NX", "PX", 3000);
        if ("OK".equals(ret)) {
            local.set(uuid);
            return true;
        }
        return false;
    }

    public static void unLock() {
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                "    return redis.call(\"del\",KEYS[1]);\n" +
                "else\n" +
                "    return 0;\n" +
                "end";
        String value = local.get();
        Jedis jedis = new Jedis("127.0.0.1");
        jedis.eval(script, Arrays.asList(KEY), Arrays.asList(value));
    }
}
